package com.diandian.backend.douyin.life.exchange.service;

import com.alibaba.fastjson2.JSON;
import com.diandian.douyin.life.boot.starter.constants.DouyinLifeBusinessConstant;
import com.diandian.douyin.life.boot.starter.dto.response.DouyinLifeTokenCacheData;
import com.diandian.douyin.life.boot.starter.dto.response.DouyinLifeTokenDataResponse;
import com.diandian.douyin.life.boot.starter.dto.response.DouyinLifeTokenResponse;
import com.diandian.douyin.life.boot.starter.service.token.DouyinLifeTokenBasicService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class DouyinLifeTokenBusinessService {

    private static final Logger logger = LoggerFactory.getLogger(DouyinLifeTokenBusinessService.class);

    @Autowired
    private DouyinLifeTokenBasicService tokenService;

    @Autowired
    private RedisTemplate redisTemplate;

    public String getToken(String clientKey, String clientSecret){
        String token = "";
        try{
            token = getTokenDTO(clientKey, clientSecret).getAccess_token();
        } catch (Exception e){
            logger.error("获取抖音本地生活token时出错", e);
            e.printStackTrace();
        }

        if(token == null || "".equals(token)){
            throw new RuntimeException("获取抖音本地生活token时出错");
        }

        return token;
    }

    /**
     * 获取token
     * @param clientKey
     * @param clientSecret
     * @return
     */
    public DouyinLifeTokenCacheData getTokenDTO(String clientKey, String clientSecret) throws Exception{

        String cacheKey = DouyinLifeBusinessConstant.DOUYIN_LIFE_TOKEN_CACHE_KEY_PREFIX + clientKey;
        DouyinLifeTokenCacheData newTokenDTO;

        // 从缓存获取数据
        String token = getFromCache(cacheKey);

        // 缓存中没有，则执行更新token
        if(token == null || "".equals(token)){
            logger.info("未从缓存中获取到抖音本地生活token数据...");
            newTokenDTO = updateToken(clientKey, clientSecret, cacheKey);
            return newTokenDTO;
        }

        // 数据结构转换
        DouyinLifeTokenCacheData cacheData = JSON.parseObject(token, DouyinLifeTokenCacheData.class);

        // 缓存中token的已过有效期
        Date expiresDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(cacheData.getExpires_time());
        boolean isExpiresFlag = expiresDate.before(new Date());
        if(isExpiresFlag){
            logger.info("从缓存中获取的抖音本地生活token已过期，将重新进行token获取...");
            newTokenDTO = updateToken(clientKey, clientSecret, cacheKey);
            return newTokenDTO;
        }

        logger.info("从缓存中获取抖音本地生活token成功，token信息：" + JSON.toJSONString(cacheData));

        return cacheData;
    }

    /**
     * 调用抖音获取新的token，刷新缓存中的token
     * @param clientKey
     * @param clientSecret
     * @param cacheKey
     */
    private DouyinLifeTokenCacheData updateToken(String clientKey, String clientSecret, String cacheKey){

        // 从抖音获取token
        DouyinLifeTokenResponse tokenResponse = tokenService.getToken(clientKey, clientSecret);
        DouyinLifeTokenDataResponse tokenDTO = tokenResponse.getData();

        logger.info("调用抖音本地生活获取token：" + JSON.toJSONString(tokenDTO));

        // 转换数据结构
        DouyinLifeTokenCacheData cacheData = new DouyinLifeTokenCacheData(tokenDTO);

        logger.info("转换token数据结构：" + JSON.toJSONString(cacheData));

        // 设置缓存
        setCache(cacheKey, JSON.toJSONString(cacheData));

        return cacheData;
    }

    /**
     * 从缓存中获取数据
     * @param key 缓存的key
     * @return 缓存的json字符串
     */
    private String getFromCache(String key){
        Object tokenObject = redisTemplate.opsForValue().get(key);
        return tokenObject == null ? null : String.valueOf(tokenObject);
    }

    private boolean setCache(String key, String token){
        redisTemplate.opsForValue().set(key, token);
        return true;
    }

}
